package de.gbeine.java.ebookmanager.tag;

import java.util.Set;

import org.yaml.snakeyaml.constructor.AbstractConstruct;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;

import de.gbeine.java.ebookmanager.yaml.DataFetcher;
import de.gbeine.java.ebookmanager.yaml.NodeSelector;

/**
 *
 */
final class TagConstructor extends Constructor {

    /**
     *
     */
    private static final NodeSelector NAME_NODE_SELECTOR = new NodeSelector("name");

    /**
     *
     */
    private static final NodeSelector SUBTAGS_NODE_SELECTOR = new NodeSelector("subtags");

    /**
     *
     */
    public TagConstructor() {
        this.yamlConstructors.put(new org.yaml.snakeyaml.nodes.Tag("!tag"), new ConstructTag());
    }

    /**
     *
     */
    private class ConstructTag extends AbstractConstruct {
        public Object construct(final Node node) {
            final MappingNode map = (MappingNode) node;
            final String tagName = DataFetcher.fetchValue(map, TagConstructor.NAME_NODE_SELECTOR);

            final Tag tag = new Tag(tagName);

            final Set<Node> subNodes = DataFetcher.fetchNodes(map, TagConstructor.SUBTAGS_NODE_SELECTOR);

            for (final Node subNode : subNodes) {
                tag.add((Tag) TagConstructor.this.constructObject(subNode));
            }

            return tag;
        }
    }
}
